/*
 * @(#)SetCookieDirective.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.result.template.directive;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.nhncorp.usf.core.Constants;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author Web Platform Development Team
 */
public class SetCookieDirective extends AbstractTemplateDirectiveModel {
    public static final String COOKIE_DEFAULT_PATH = "/";

    @SuppressWarnings("unchecked")
	private Map usfDataModel;

    /**
     * Instantiates a new sets the cookie directive.
     *
     * @param dataModel the data model
     */
    @SuppressWarnings("unchecked")
	public SetCookieDirective(Map dataModel) {
        usfDataModel = dataModel;
    }

    /**
     * @param env      Environment
     * @param params   Map
     * @param loopVars TemplateModel
     * @param body     TemplateDirectiveBody
     * @throws TemplateException the TemplateException
     * @throws IOException       the IOException
     * @see freemarker.template.TemplateDirectiveModel#execute(freemarker.core.Environment, java.util.Map, freemarker.template.TemplateModel[], freemarker.template.TemplateDirectiveBody)
     */
    @SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        String key = getAsString(params.get("key"));
        String value = getAsString(params.get("value"));
        String domain = getAsString(params.get("domain"));
        String path = getAsString(params.get("path"));
        Boolean secure = getAsBoolean(params.get("secure"));
        Integer maxAge = getAsInteger(params.get("maxage"));

        HttpServletResponse response = (HttpServletResponse)usfDataModel.get(Constants.FREEMARKER_KEY_RESPONSE);

        if (key != null && value != null) {
            Cookie cookie = new Cookie(key, value);

            if (domain != null) {
                cookie.setDomain(domain);
            }
            if (path != null) {
                cookie.setPath(path);
            }
            if (secure != null) {
                cookie.setSecure(secure);
            }
            if (maxAge != null) {
                cookie.setMaxAge(maxAge);
            }

            response.addCookie(cookie);
        }
    }
}
